//
//  ViewController.m
//  chenbeibeiMap
//
//  Created by lanou on 15/12/23.
//  Copyright © 2015年 吴昊. All rights reserved.
//

#import "ViewController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>


@interface ViewController ()<MAMapViewDelegate,AMapSearchDelegate,UISearchBarDelegate,UISearchResultsUpdating>
{
    
    MAMapView *_mapView;
    AMapSearchAPI *_search;//搜索
    MAPointAnnotation *_destinationPoint;//目的地
    
}

@property (nonatomic,strong)NSArray *pathPolylines;//返回路径分段的数组

//搜索功能
@property (nonatomic,strong)UISearchController *searchController;


@end

@implementation ViewController

//懒加载
- (NSArray *)pathPolylines{
    if (_pathPolylines == nil) {
        _pathPolylines = [[NSArray alloc]init];
    }
    return _pathPolylines;
}




- (void)viewDidLoad {
    [super viewDidLoad];
//    aa7b567e476aa0a673ca6e41829469c5
    
    //配置用户Key
    [MAMapServices sharedServices].apiKey = @"aa7b567e476aa0a673ca6e41829469c5";
    
    //搜索
    [AMapSearchServices sharedServices].apiKey = @"aa7b567e476aa0a673ca6e41829469c5";
    

    
    
    
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _mapView.delegate = self;
    
    [self.view addSubview:_mapView];
    
    //定位
    _mapView.showsUserLocation = YES;
    _mapView.showTraffic = YES;//显示交通状况
//    _mapView.mapType = MAMapTypeSatellite;//显示卫星地图
    _mapView.userTrackingMode = MAUserTrackingModeFollow;//跟随模式
    _mapView.zoomLevel  = 14;//缩放比例
    
    
    //初始化检索对象
    _search = [[AMapSearchAPI alloc]init];
    _search.delegate =self;
    
//    //左边的按钮
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(searching)];
    self.navigationItem.leftBarButtonItem =left;
    
    // 中间搜索按钮
//    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(kWidth / 2 - 20, 30, 50, 20)];
//    [searchButton setTitle:@"搜索" forState:(UIControlStateNormal)];
//    [searchButton setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
//    [searchButton addTarget:self action:@selector(search) forControlEvents:(UIControlEventTouchUpInside)];
//    [self.navigationController.view addSubview:searchButton];
    
    //右边的按钮
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemDone) target:self action:@selector(lujing)];
    
    self.navigationItem.rightBarButtonItem =right;

    

    
   
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)searching{
    
    //创建搜索功能
//    self.searchController = [[UISearchController alloc]initWithSearchResultsController:self];
//    self.searchController.searchResultsUpdater =self;
//    self.searchController.searchBar.delegate =self;
//    
//    self.searchController.dimsBackgroundDuringPresentation = NO;
//    self.searchController.hidesNavigationBarDuringPresentation = NO;
//    [self.searchController.searchBar sizeToFit];
//    [self presentViewController:self.searchController animated:YES completion:nil];
//    
//    
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc]init];
    
    
    request.location = [AMapGeoPoint locationWithLatitude:_mapView.userLocation.coordinate.latitude longitude:_mapView.userLocation.coordinate.longitude];
  
    request.keywords = @"建材市场";
    // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
    // POI的类型共分为20种大类别，分别为：
    // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
    // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
    // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
    
  //  request.types = @"住宿服务|商务住宅";
    
    request.requireExtension = YES;
    
    //发起周边搜索
    [_search AMapPOIAroundSearch:request];
    
}



//- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
//    
//    //1.获取输入值
//    NSString *conditionStr = searchController.searchBar.text;
//    
//    //2.创建谓词，准备进行判断的工具
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.dataArray CONTAINS [C] %@",conditionStr];
//   
//    
//    
//}



#pragma mark - 搜索回调方法
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if(response.pois.count == 0)
    {
        return;
    }
    //通过 AMapPOISearchResponse 对象处理搜索结果
    for (AMapPOI *poi in response.pois) {
        
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
        
        annotation.title = poi.name;
        annotation.subtitle = poi.address;
        
        [_mapView addAnnotation:annotation];
    }
}
//大头针显示
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *identifer = @"annot";
        MAPinAnnotationView *view = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifer];
        
        if (!view) {
            view = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifer];
        }
        
        view.canShowCallout = YES;
        
        view.animatesDrop = YES;
        
        return view;
    }
    return nil;
}

#pragma mark - 显示路径
- (void)lujing
{
    [self pathActionWithLocation:_destinationPoint];
    
}

- (void)pathActionWithLocation:(MAPointAnnotation *)annotation
{
    
    AMapWalkingRouteSearchRequest *request = [[AMapWalkingRouteSearchRequest alloc] init];
    
    request.origin = [AMapGeoPoint locationWithLatitude:_mapView.userLocation.location.coordinate.latitude longitude:_mapView.userLocation.location.coordinate.longitude];
    
    request.destination = [AMapGeoPoint locationWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
    
    
    [_search AMapWalkingRouteSearch:request];
}
//回调路径
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.count > 0)
    {
        [_mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
        
        // 只显示第一条
        self.pathPolylines = [self polylinesForPath:response.route.paths[0]];
        
        [_mapView addOverlays:self.pathPolylines];
    }
    
}

- (NSArray *)polylinesForPath:(AMapPath *)path
{
    if (path == nil || path.steps.count == 0)
    {
        return nil;
    }
    
    NSMutableArray *polylines = [NSMutableArray array];
    
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL *stop) {
        
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline coordinateCount:&count parseToken:@";"];
        
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
        
        free(coordinates), coordinates = NULL;
        
    }];
    
    return polylines;
}
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token
{
    if (string == nil)
    {
        return NULL;
    }
    
    if (token == nil)
    {
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","])
    {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }
    
    else
    {
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL)
    {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++)
    {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    
    return coordinates;
}

//展示路径
- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        
        polylineView.lineWidth   = 4;
        polylineView.strokeColor = [UIColor magentaColor];
        
        return polylineView;
    }
    
    return nil;
}
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    _destinationPoint = view.annotation;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
